-- Tags: no-object-storage, no-parallel, no-fasttest
-- no-object-storage: s3 has 20 more threads
-- no-parallel: it checks the number of threads, which can be lowered in presence of other queries

-- avoid settings randomization by clickhouse-test
{% set max_threads = namespace(value=10) %}

set max_threads = {{ max_threads.value }};

-- more blocks to process
set max_block_size = 10;
set min_insert_block_size_rows = 10;

set materialized_views_ignore_errors = 1;

drop table if exists testX;
drop table if exists testXA;
drop table if exists testXB;
drop table if exists testXC;

create table testX (A Int64) engine=MergeTree order by tuple();

create materialized view testXA engine=MergeTree order by tuple() as select sleep(0.1) from testX;
create materialized view testXB engine=MergeTree order by tuple() as select sleep(0.2), throwIf(A=1) from testX;
create materialized view testXC engine=MergeTree order by tuple() as select sleep(0.1) from testX;


{% set count = namespace(value=0) %}

-- { echoOn }
{% for max_insert_threads in [0, 5] %}
{% for parallel_view_processing in [0, 1] %}
{% for optimize_trivial_insert_select in [0, 1] %}

{% set count.value = count.value + 1 %}

insert into testX select number from numbers(50) settings
    send_logs_level='fatal',
    insert_deduplication_token='UT_{{ count.value }}',
    log_queries=1,
    max_insert_threads={{ max_insert_threads }},
    parallel_view_processing={{ parallel_view_processing }},
    optimize_trivial_insert_select={{ optimize_trivial_insert_select }};

select count() from testX;
select count() from testXA;
select count() from testXC;
{% endfor %}
{% endfor %}
{% endfor %}

system flush logs system.query_log;

select
    peak_threads_usage,
    Settings['max_threads'] as max_threads,
    Settings['max_insert_threads'] as max_insert_threads,
    Settings['parallel_view_processing'] as parallel_view_processing,
    Settings['optimize_trivial_insert_select'] as optimize_trivial_insert_select
from system.query_log where
    current_database = currentDatabase() and
    type != 'QueryStart' and
    query like '%insert into testX %'
order by ALL;

-- { echoOff }

drop table testX;
drop view testXA;
drop view testXB;
drop view testXC;
